/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.util;

/**
 * 链表元素
 * 
 * @author jianggujin
 *
 * @param <T>
 */
public class JLinkedEntry<T, V> {
    private final T key;
    private V value;
    private JLinkedEntry<T, V> next;
    private JLinkedEntry<T, V> prev;

    public JLinkedEntry(T key) {
        this(null, key, null, null);
    }

    public JLinkedEntry(T key, V value) {
        this(null, key, value, null);
    }

    public JLinkedEntry(JLinkedEntry<T, V> prev, T key, V value, JLinkedEntry<T, V> next) {
        JAssert.notNull(key, "key不能为空");
        this.key = key;
        this.value = value;
        this.next = next;
        this.prev = prev;
    }

    public boolean isHead() {
        return this.prev == null;
    }

    public boolean isTail() {
        return this.next == null;
    }

    public void setHead() {
        this.prev = null;
    }

    public void setTail() {
        this.next = null;
    }

    public T getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public JLinkedEntry<T, V> getNext() {
        return next;
    }

    public void setNext(JLinkedEntry<T, V> next) {
        this.next = next;
        if (next != null) {
            next.prev = this;
        }
    }

    public JLinkedEntry<T, V> getPrev() {
        return prev;
    }

    public void setPrev(JLinkedEntry<T, V> prev) {
        this.prev = prev;
        if (prev != null) {
            prev.next = this;
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("isHead:").append(isHead()).append("\r\n");
        int depth = 0;
        JLinkedEntry<T, V> current = this;
        while (current != null) {
            for (int i = 0; i < depth; i++) {
                builder.append("\t");
            }
            builder.append("key:").append(current.getKey()).append(", value:").append(current.getValue())
                    .append("\r\n");
            current = current.getNext();
        }
        return builder.toString();
    }
}
